package com.wjcxf.view;

import com.wjcxf.entry.DeviceEntry;
import com.wjcxf.solution.PopStarSolution;
import com.wjcxf.struct.PopStar;
import com.wjcxf.utils.AdbUtil;
import com.wjcxf.utils.PropertiesUtil;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 我叫程晓非
 * @desc MainFrame 主窗口类
 * @date 2022-03-15
 * @version 1.0
 */
public class MainFrame extends JFrame implements ActionListener, ItemListener, KeyListener {
    public final static String USER_CONFIG_FOLDER = "config";
    public final static String USER_SCREENSHOT_FOLDER = "screenshot";
    public final static String USER_CONFIG_SUFFIX = ".properties";

    public final static String IMAGE_APPLICATION_ICON = "src/image/star.png";

    public final static String IMAGE_UP_BUTTON = "src/image/up.png";
    public final static String IMAGE_DOWN_BUTTON = "src/image/down.png";
    public final static String IMAGE_RIGHT_BUTTON = "src/image/right.png";
    public final static String IMAGE_LEFT_BUTTON = "src/image/left.png";

    public final static String IMAGE_START_BUTTON = "src/image/start.png";
    public final static String IMAGE_SAVE_BUTTON = "src/image/save.png";

    public final static String IMAGE_MINIMIZE_ICON = "src/image/minimize.png";

    public final static String IMAGE_CLOSE_ICON = "src/image/close.png";

    private JPanel framePanel;
    private JPanel mainPanel;

    private ScreenshotPanel screenshotPanel;
    private JPanel controlPanel;
    private boolean isRun = false;
    //截图区域
    private JLabel screenshotLabel = new JLabel();

    //设备列表，key-id,value-型号
    private HashMap<String,String> deviceMap=new HashMap<>();
    private final JComboBox<DeviceEntry<String,String>> deviceComboBox = new JComboBox<>();

    private DeviceEntry<String,String> selectedDeviceEntry = null;

    private Thread refreshThread = null;


    private PopStar popStar = null;


    //连接状态
    private JLabel connectStatusLabel = new JLabel("连接状态:");
    private JLabel connectStatusText = new JLabel("未连接");
    private JLabel selectDeviceLabel = new JLabel("当前设备:");

    private JButton connectButton = new JButton("连接");
    private JButton refreshButton = new JButton("刷新");

    private JLabel resolutionRatioLabel = new JLabel("设备分辨率:");
    private JLabel showResolutionRatioText = new JLabel("...");



    private JLabel locationLabel = new JLabel("位置微调:");
    private JButton leftLocationButton = new JButton();
    private JButton rightLocationButton = new JButton();
    private JButton upLocationButton = new JButton();
    private JButton downLocationButton = new JButton();


    private JLabel scaleLabel = new JLabel("尺寸微调:");
    private JButton leftScaleButton = new JButton();
    private JButton rightScaleButton = new JButton();
    private JButton upScaleButton = new JButton();
    private JButton downScaleButton = new JButton();



    private JButton startButton = new JButton();
    private JButton saveButton = new JButton();


    private JButton minimizeButton;
    private JButton closeButton;

    private JLabel threadNumberLabel = new JLabel("线程数量:");
    private JTextField threadNumberTextField = new JTextField(10);


    private JLabel searchTimeLabel = new JLabel("每步搜索时间(ms):");
    private JTextField searchTimeTextField = new JTextField(10);



    //多线程设置

    private JLabel multiThreadLabel = new JLabel("是否多线程加速:");
    private ButtonGroup buttonGroup = new ButtonGroup();
    JRadioButton button;
    JRadioButton button2;

    private JLabel expectLabel = new JLabel("期望分数:");
    private JLabel expectScoreLabel = new JLabel("0");
    //拖动功能
    Point origin = new Point();
    public MainFrame(){
        //检查是否存在配置文件，没有就加上
        File userConfigFolder = new File("./"+USER_CONFIG_FOLDER);
        File userScreenshotFolder = new File("./"+USER_SCREENSHOT_FOLDER);
        File userConfigFile = new File("./"+USER_CONFIG_FOLDER+"/"+"default"+USER_CONFIG_SUFFIX);
        if(!userConfigFolder.exists()){
            userConfigFolder.mkdir();
        }
        if(!userScreenshotFolder.exists()){
            userScreenshotFolder.mkdir();
        }
        if(!userConfigFile.exists()){
            PropertiesUtil.writeValue(userConfigFile.getAbsolutePath(),"grid.x","0");
            PropertiesUtil.writeValue(userConfigFile.getAbsolutePath(),"grid.y","0");
            PropertiesUtil.writeValue(userConfigFile.getAbsolutePath(),"grid.width","280");
            PropertiesUtil.writeValue(userConfigFile.getAbsolutePath(),"grid.height","280");
            PropertiesUtil.writeValue(userConfigFile.getAbsolutePath(),"screen.height","1920");
            PropertiesUtil.writeValue(userConfigFile.getAbsolutePath(),"screen.width","1080");
            PropertiesUtil.writeValue(userConfigFile.getAbsolutePath(),"config.multithreading","0");
            PropertiesUtil.writeValue(userConfigFile.getAbsolutePath(),"config.threadnum","4");
            PropertiesUtil.writeValue(userConfigFile.getAbsolutePath(),"config.searchtime","8000");
        }
        isRun  = true;
        screenshotLabel.setBackground(Color.BLUE);

        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        initView();
        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                isRun = false;
                if(refreshThread!=null){
                    refreshThread.interrupt();
                }
                super.windowClosing(e);

            }
        });
        setVisible(true);
        //设置居中
        setLocationRelativeTo(null);
        setResizable(false);
        ScreenshotPanel.PANEL_WIDTH = screenshotPanel.getWidth();
        ScreenshotPanel.PANEL_HEIGHT = screenshotPanel.getHeight();

        //判断有没有初始设置，没有就居中
        String gridXStr = PropertiesUtil.readValue(userConfigFile.getAbsolutePath(),"grid.x");
        String gridYStr = PropertiesUtil.readValue(userConfigFile.getAbsolutePath(),"grid.y");
        int gridX = 0;
        int gridY = 0;
        if("0".equals(gridXStr) || "0".equals(gridYStr)){
            gridX = (screenshotPanel.getWidth() - screenshotPanel.getGrid().getWidth())/2;
            gridY = (screenshotPanel.getHeight() - screenshotPanel.getGrid().getHeight())/2;
        }else{
            gridX = Integer.parseInt(gridXStr);
            gridY = Integer.parseInt(gridYStr);
        }

//        System.out.println(gridX+","+gridY);
        screenshotPanel.getGrid().setX(gridX);
        screenshotPanel.getGrid().setY(gridY);
        this.addKeyListener(this);
        this.setFocusable(true);
    }
    private void initView(){
        this.setIconImage(new ImageIcon(IMAGE_APPLICATION_ICON).getImage());
        this.setSize(880,770);
        mainPanel = new JPanel();
        mainPanel.setLayout(new GridLayout(1,2,3,3));
        this.setUndecorated(true);
        initScreenshotPanel();
        initControlPanel();

        framePanel = new JPanel();
        framePanel.setLayout(null);
        framePanel.setBounds(0,0,880,750);
        mainPanel.setBounds(5,45,870,730);
        framePanel.setBackground(Color.CYAN);
        minimizeButton = new JButton();
        closeButton = new JButton();
        minimizeButton.setBounds(770,0,55,25);

        minimizeButton.setIcon(new ImageIcon(IMAGE_MINIMIZE_ICON));
        closeButton.setBounds(825,0,55,25);
        closeButton.setIcon(new ImageIcon(IMAGE_CLOSE_ICON));
        framePanel.add(minimizeButton);
        framePanel.add(closeButton);
        framePanel.add(mainPanel);
        add(framePanel);
        framePanel.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                framePanel.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                origin.x = e.getX();
                origin.y = e.getY();
                super.mousePressed(e);
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                framePanel.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
//                origin.x = e.getX();
//                origin.y = e.getY();
                super.mouseReleased(e);
            }

            @Override
            public void mouseEntered(MouseEvent e) {
                framePanel.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                super.mouseEntered(e);
            }
        });
        framePanel.addMouseMotionListener(new MouseMotionAdapter() {
            @Override
            public void mouseDragged(MouseEvent e) {
                framePanel.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
                Point p = getLocation();
                setLocation(p.x + (e.getX() - origin.x),p.y + (e.getY() - origin.y));
                super.mouseDragged(e);
            }
        });
        minimizeButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                setExtendedState(JFrame.ICONIFIED);
            }
        });
        closeButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });


    }

    private void initControlPanel() {

        File userConfigFile = new File("./"+USER_CONFIG_FOLDER+"/"+"default"+USER_CONFIG_SUFFIX);
        GridBagLayout gridBagLayout=new GridBagLayout();
        controlPanel = new JPanel();
        controlPanel.setLayout(gridBagLayout);
        controlPanel.setBorder(BorderFactory.createTitledBorder("状态栏"));
        //row1 连接状态
        GridBagConstraints gba_line11=new GridBagConstraints();
        gba_line11.insets = new Insets(0,10,5,5);
        gba_line11.gridx = 0;
        gba_line11.gridy = 0;
//        gba_line11.weightx=10.0;
        gridBagLayout.setConstraints(connectStatusLabel,gba_line11);
        controlPanel.add(connectStatusLabel);


        GridBagConstraints gba_line12=new GridBagConstraints();
        gba_line12.insets = new Insets(0,10,5,5);
        gba_line12.gridx = 1;
        gba_line12.gridy = 0;
//        gba_line12.weightx=10.0;
//        gba_line12.gridwidth = GridBagConstraints.REMAINDER;
        gridBagLayout.setConstraints(connectStatusText,gba_line12);
        controlPanel.add(connectStatusText);
        //row2 设备刷新
        GridBagConstraints gba_line21=new GridBagConstraints();
        gba_line21.insets = new Insets(0,10,5,5);
        gba_line21.gridx = 0;
        gba_line21.gridy = 1;
//        gba_line21.weightx=10.0;
        gridBagLayout.setConstraints(selectDeviceLabel,gba_line21);
        controlPanel.add(selectDeviceLabel);


        GridBagConstraints gba_line22=new GridBagConstraints();
        gba_line22.insets = new Insets(0,10,5,5);
        gba_line22.gridx = 1;
        gba_line22.gridy = 1;
//        gba_line22.weightx=10.0;
//        gba_line22.gridwidth = GridBagConstraints.REMAINDER;
        gridBagLayout.setConstraints(deviceComboBox,gba_line22);
        deviceComboBox.addItemListener(this);
        deviceComboBox.setSize(65,30);
        controlPanel.add(deviceComboBox);
        if(deviceComboBox.getItemCount() == 0){
            deviceComboBox.addItem(new DeviceEntry<String, String>("0","请选择设备"));
        }

        GridBagConstraints gba_line23=new GridBagConstraints();
        gba_line23.insets = new Insets(0,10,5,5);
        gba_line23.gridx = 2;
        gba_line23.gridy = 1;
        gridBagLayout.setConstraints(connectButton,gba_line23);
        connectButton.setActionCommand("connectButton");
        connectButton.addActionListener(this);
        controlPanel.add(connectButton);

        GridBagConstraints gba_line24=new GridBagConstraints();
        gba_line24.insets = new Insets(0,10,5,5);
        gba_line24.gridx = 3;
        gba_line24.gridy = 1;
        gridBagLayout.setConstraints(refreshButton,gba_line24);
        refreshButton.setActionCommand("refreshButton");
        refreshButton.addActionListener(this);
        controlPanel.add(refreshButton);


        //row3 分辨率
        GridBagConstraints gba_line31=new GridBagConstraints();
        gba_line31.insets = new Insets(0,10,5,5);
        gba_line31.gridx = 0;
        gba_line31.gridy = 2;
        gridBagLayout.setConstraints(resolutionRatioLabel,gba_line31);
        controlPanel.add(resolutionRatioLabel);


        GridBagConstraints gba_line32=new GridBagConstraints();
        gba_line32.insets = new Insets(0,10,5,5);
        gba_line32.gridx = 1;
        gba_line32.gridy = 2;
        gridBagLayout.setConstraints(showResolutionRatioText,gba_line32);
        controlPanel.add(showResolutionRatioText);

        //row4 位置微调
        GridBagConstraints gba_line41=new GridBagConstraints();
        gba_line41.insets = new Insets(0,10,5,5);
        gba_line41.gridx = 0;
        gba_line41.gridy = 3;


        gridBagLayout.setConstraints(locationLabel,gba_line41);
        controlPanel.add(locationLabel);
        //row5 位置微调按钮
        GridBagConstraints gba_line52=new GridBagConstraints();
        gba_line52.insets = new Insets(0,10,5,5);
        gba_line52.gridx = 1;
        gba_line52.gridy = 4;
        gba_line52.fill = GridBagConstraints.CENTER;
        gridBagLayout.setConstraints(upLocationButton,gba_line52);
        upLocationButton.setSize(41,41);
        upLocationButton.setContentAreaFilled(false);
        upLocationButton.setPreferredSize(new Dimension(41,41));
        upLocationButton.setIcon(new ImageIcon(IMAGE_UP_BUTTON));
        controlPanel.add(upLocationButton);

        //row6 位置微调按钮
        GridBagConstraints gba_line61=new GridBagConstraints();
        gba_line61.insets = new Insets(0,10,5,5);
        gba_line61.gridx = 0;
        gba_line61.gridy = 5;
        gridBagLayout.setConstraints(leftLocationButton,gba_line61);
        leftLocationButton.setSize(41,41);
        leftLocationButton.setContentAreaFilled(false);
        leftLocationButton.setPreferredSize(new Dimension(41,41));
        leftLocationButton.setIcon(new ImageIcon(IMAGE_LEFT_BUTTON));
        controlPanel.add(leftLocationButton);

        GridBagConstraints gba_line62=new GridBagConstraints();
        gba_line62.insets = new Insets(0,10,5,5);
        gba_line62.gridx = 1;
        gba_line62.gridy = 5;
        gridBagLayout.setConstraints(downLocationButton,gba_line62);
        downLocationButton.setSize(41,41);
        downLocationButton.setContentAreaFilled(false);
        downLocationButton.setPreferredSize(new Dimension(41,41));
        downLocationButton.setIcon(new ImageIcon(IMAGE_DOWN_BUTTON));
        controlPanel.add(downLocationButton);

        GridBagConstraints gba_line63=new GridBagConstraints();
        gba_line63.insets = new Insets(0,10,5,5);
        gba_line63.gridx = 2;
        gba_line63.gridy = 5;
        gridBagLayout.setConstraints(rightLocationButton,gba_line63);
        rightLocationButton.setSize(41,41);
        rightLocationButton.setContentAreaFilled(false);
        rightLocationButton.setPreferredSize(new Dimension(41,41));
        rightLocationButton.setIcon(new ImageIcon(IMAGE_RIGHT_BUTTON));
        controlPanel.add(rightLocationButton);

        //row7 尺寸微调Label
        GridBagConstraints gba_line71=new GridBagConstraints();
        gba_line71.insets = new Insets(0,10,5,5);
        gba_line71.gridx = 0;
        gba_line71.gridy = 6;
        gridBagLayout.setConstraints(scaleLabel,gba_line71);
        controlPanel.add(scaleLabel);


        //row8 位置微调Button
        GridBagConstraints gba_line82=new GridBagConstraints();
        gba_line82.insets = new Insets(0,10,5,5);
        gba_line82.gridx = 1;
        gba_line82.gridy = 7;
        gridBagLayout.setConstraints(upScaleButton,gba_line82);
        upScaleButton.setSize(41,41);
        upScaleButton.setContentAreaFilled(false);
        upScaleButton.setPreferredSize(new Dimension(41,41));
        upScaleButton.setIcon(new ImageIcon(IMAGE_UP_BUTTON));
        controlPanel.add(upScaleButton);

        //row9 尺寸微调按钮
        GridBagConstraints gba_line91=new GridBagConstraints();
        gba_line91.insets = new Insets(0,10,5,5);
        gba_line91.gridx = 0;
        gba_line91.gridy = 8;
        gridBagLayout.setConstraints(leftScaleButton,gba_line91);
        leftScaleButton.setSize(41,41);
        leftScaleButton.setContentAreaFilled(false);
        leftScaleButton.setPreferredSize(new Dimension(41,41));
        leftScaleButton.setIcon(new ImageIcon(IMAGE_LEFT_BUTTON));
        controlPanel.add(leftScaleButton);

        GridBagConstraints gba_line92=new GridBagConstraints();
        gba_line92.insets = new Insets(0,10,5,5);
        gba_line92.gridx = 1;
        gba_line92.gridy = 8;
        gridBagLayout.setConstraints(downScaleButton,gba_line92);
        downScaleButton.setSize(41,41);
        downScaleButton.setContentAreaFilled(false);
        downScaleButton.setPreferredSize(new Dimension(41,41));
        downScaleButton.setIcon(new ImageIcon(IMAGE_DOWN_BUTTON));
        controlPanel.add(downScaleButton);

        GridBagConstraints gba_line93=new GridBagConstraints();
        gba_line93.insets = new Insets(0,10,5,5);
        gba_line93.gridx = 2;
        gba_line93.gridy = 8;
        gridBagLayout.setConstraints(rightScaleButton,gba_line93);
        rightScaleButton.setSize(41,41);
        rightScaleButton.setContentAreaFilled(false);
        rightScaleButton.setPreferredSize(new Dimension(41,41));
        rightScaleButton.setIcon(new ImageIcon(IMAGE_RIGHT_BUTTON));
        controlPanel.add(rightScaleButton);
        controlPanel.setBounds(0,0,426,720);
        controlPanel.setVisible(true);
        String multithreadingStr = PropertiesUtil.readValue(userConfigFile.getAbsolutePath(),"config.multithreading");
        int multithreading = Integer.parseInt(multithreadingStr);
        button =  new JRadioButton("是", multithreading == 1);
        button2 =  new JRadioButton("否", multithreading == 0);
        button.setActionCommand("isMultithreading1");
        button2.setActionCommand("isMultithreading2");
        buttonGroup.add(button);
        buttonGroup.add(button2);
        button.addActionListener(this);
        button2.addActionListener(this);



        //row10
        GridBagConstraints gba_line10_1=new GridBagConstraints();
        gba_line10_1.insets = new Insets(0,10,5,5);
        gba_line10_1.gridx = 0;
        gba_line10_1.gridy = 9;
        gridBagLayout.setConstraints(multiThreadLabel,gba_line10_1);
        controlPanel.add(multiThreadLabel);

        GridBagConstraints gba_line10_2=new GridBagConstraints();
        gba_line10_2.insets = new Insets(0,10,5,5);
        gba_line10_2.gridx = 1;
        gba_line10_2.gridy = 9;
        gridBagLayout.setConstraints(button,gba_line10_2);
        controlPanel.add(button);

        GridBagConstraints gba_line10_3=new GridBagConstraints();
        gba_line10_3.insets = new Insets(0,10,5,5);
        gba_line10_3.gridx = 2;
        gba_line10_3.gridy = 9;
        gridBagLayout.setConstraints(button2,gba_line10_3);
        controlPanel.add(button2);


        //row11
        GridBagConstraints gba_line11_1=new GridBagConstraints();
        gba_line11_1.insets = new Insets(0,10,5,5);
        gba_line11_1.gridx = 0;
        gba_line11_1.gridy = 10;
        gridBagLayout.setConstraints(threadNumberLabel,gba_line11_1);
        controlPanel.add(threadNumberLabel);

        GridBagConstraints gba_line11_2=new GridBagConstraints();
        gba_line11_2.insets = new Insets(0,10,5,5);
        gba_line11_2.gridx = 1;
        gba_line11_2.gridy = 10;
        gba_line11_2.gridwidth = 2;
        threadNumberTextField.setBounds(0,0,180,28);

        gridBagLayout.setConstraints(threadNumberTextField,gba_line11_2);
        threadNumberTextField.setDocument(new InputCharFilter());
        String threadNumStr = PropertiesUtil.readValue(userConfigFile.getAbsolutePath(),"config.threadnum");
        int threadNum = Integer.parseInt(threadNumStr);
        if(threadNum >=0 ){
            threadNumberTextField.setText(threadNum+"");
        }
        controlPanel.add(threadNumberTextField);


        //row12
        GridBagConstraints gba_line12_1=new GridBagConstraints();
        gba_line12_1.insets = new Insets(0,10,5,5);
        gba_line12_1.gridx = 0;
        gba_line12_1.gridy = 11;
        gridBagLayout.setConstraints(searchTimeLabel,gba_line12_1);
        controlPanel.add(searchTimeLabel);

        GridBagConstraints gba_line12_2=new GridBagConstraints();
        gba_line12_2.insets = new Insets(0,10,5,5);
        gba_line12_2.gridx = 1;
        gba_line12_2.gridy = 11;
        gba_line12_2.gridwidth = 2;
        searchTimeTextField.setSize(180,28);
        gridBagLayout.setConstraints(searchTimeTextField,gba_line12_2);
        searchTimeTextField.setDocument(new InputCharFilter());
        //默认值设置

        String searchTimeStr = PropertiesUtil.readValue(userConfigFile.getAbsolutePath(),"config.searchtime");
        int searchTime = Integer.parseInt(searchTimeStr);
        if(searchTime >=0 ){
            searchTimeTextField.setText(searchTime+"");
        }
        controlPanel.add(searchTimeTextField);



        //row13
        GridBagConstraints gba_line13_1=new GridBagConstraints();
        gba_line13_1.insets = new Insets(0,10,5,5);
        gba_line13_1.gridx = 0;
        gba_line13_1.gridy = 12;
        gridBagLayout.setConstraints(saveButton,gba_line13_1);
        saveButton.setSize(80,41);
        saveButton.setContentAreaFilled(false);
        saveButton.setPreferredSize(new Dimension(80,41));
        saveButton.setIcon(new ImageIcon(IMAGE_SAVE_BUTTON));
        controlPanel.add(saveButton);

        GridBagConstraints gba_line13_2=new GridBagConstraints();
        gba_line13_2.insets = new Insets(0,10,5,5);
        gba_line13_2.gridx = 1;
        gba_line13_2.gridy = 12;
        gridBagLayout.setConstraints(startButton,gba_line13_2);
        startButton.setSize(80,41);
        startButton.setContentAreaFilled(false);
        startButton.setPreferredSize(new Dimension(80,41));
        startButton.setIcon(new ImageIcon(IMAGE_START_BUTTON));
        controlPanel.add(startButton);


        //row11
        GridBagConstraints gba_line14_1=new GridBagConstraints();
        gba_line14_1.insets = new Insets(0,10,5,5);
        gba_line14_1.gridx = 0;
        gba_line14_1.gridy = 13;
        gridBagLayout.setConstraints(expectLabel,gba_line14_1);
        controlPanel.add(expectLabel);

        GridBagConstraints gba_line14_2=new GridBagConstraints();
        gba_line14_2.insets = new Insets(0,10,5,5);
        gba_line14_2.gridx = 1;
        gba_line14_2.gridy = 13;
        gridBagLayout.setConstraints(expectScoreLabel,gba_line14_2);
        controlPanel.add(expectScoreLabel);

        leftLocationButton.setActionCommand("leftLocationButton");
        rightLocationButton.setActionCommand("rightLocationButton");
        upLocationButton.setActionCommand("upLocationButton");
        downLocationButton.setActionCommand("downLocationButton");
        leftScaleButton.setActionCommand("leftScaleButton");
        rightScaleButton.setActionCommand("rightScaleButton");
        upScaleButton.setActionCommand("upScaleButton");
        downScaleButton.setActionCommand("downScaleButton");
        saveButton.setActionCommand("saveButton");
        startButton.setActionCommand("startButton");

        leftLocationButton.setToolTipText("快捷键A");
        rightLocationButton.setToolTipText("快捷键D");
        upLocationButton.setToolTipText("快捷键W");
        downLocationButton.setToolTipText("快捷键S");
        leftScaleButton.setToolTipText("快捷键J");
        rightScaleButton.setToolTipText("快捷键L");
        upScaleButton.setToolTipText("快捷键I");
        downScaleButton.setToolTipText("快捷键K");

        leftLocationButton.addActionListener(this);
        rightLocationButton.addActionListener(this);
        upLocationButton.addActionListener(this);
        downLocationButton.addActionListener(this);
        leftScaleButton.addActionListener(this);
        rightScaleButton.addActionListener(this);
        upScaleButton.addActionListener(this);
        downScaleButton.addActionListener(this);
        saveButton.addActionListener(this);
        startButton.addActionListener(this);

        leftLocationButton.addKeyListener(this);
        rightLocationButton.addKeyListener(this);
        upLocationButton.addKeyListener(this);
        downLocationButton.addKeyListener(this);
        leftScaleButton.addKeyListener(this);
        rightScaleButton.addKeyListener(this);
        upScaleButton.addKeyListener(this);
        downScaleButton.addKeyListener(this);
        startButton.addKeyListener(this);

        startButton.setEnabled(false);



        controlPanel.setBorder(BorderFactory.createTitledBorder("控制面板"));

        mainPanel.add(controlPanel);
    }
    private void saveUserConfig(){
        saveButton.setEnabled(false);
        File userConfigFile = new File("./"+USER_CONFIG_FOLDER+"/"+"default"+USER_CONFIG_SUFFIX);
        PropertiesUtil.writeValue(userConfigFile.getAbsolutePath(),"grid.x",this.screenshotPanel.getGrid().getX()+"");
        PropertiesUtil.writeValue(userConfigFile.getAbsolutePath(),"grid.y",this.screenshotPanel.getGrid().getY()+"");
        PropertiesUtil.writeValue(userConfigFile.getAbsolutePath(),"grid.width",this.screenshotPanel.getGrid().getWidth()+"");
        PropertiesUtil.writeValue(userConfigFile.getAbsolutePath(),"grid.height",this.screenshotPanel.getGrid().getHeight()+"");
        if(this.screenshotPanel.getBufferedImage() != null){
            PropertiesUtil.writeValue(userConfigFile.getAbsolutePath(),"screen.height",this.screenshotPanel.getBufferedImage().getHeight()+"");
            PropertiesUtil.writeValue(userConfigFile.getAbsolutePath(),"screen.width",this.screenshotPanel.getBufferedImage().getWidth()+"");
        }
        if(!"".equals(this.threadNumberTextField.getText())){
            int threadNumber= Integer.parseInt(this.threadNumberTextField.getText());
            PropertiesUtil.writeValue(userConfigFile.getAbsolutePath(),"config.threadnum",threadNumber+"");
        }
        if(!"".equals(this.searchTimeTextField.getText())){
            int searchTime= Integer.parseInt(this.searchTimeTextField.getText());
            PropertiesUtil.writeValue(userConfigFile.getAbsolutePath(),"config.searchtime",searchTime+"");
        }
        JOptionPane.showMessageDialog(this,"保存成功");
        saveButton.setEnabled(true);
    }

    private void initScreenshotPanel() {

        screenshotPanel = new ScreenshotPanel();

        screenshotPanel.setBorder(BorderFactory.createTitledBorder("截图区域"));
        screenshotLabel.setBounds(0,0,426,720);
        screenshotLabel.setVisible(true);
        screenshotPanel.add(screenshotLabel);
        screenshotPanel.setBackground(new Color(0,0,0,0));
        mainPanel.add(screenshotPanel);


    }


    public void startScreenshotThread() {
        //2.开启截图进程
        if (refreshThread == null) {
            refreshThread = new Thread() {
                @Override
                public void run() {
                    while (true) {
                        //截图
                        AdbUtil.executeShellPlus("adb shell screencap -p /sdcard/screen.png");
                        AdbUtil.executeShellPlus("adb pull /sdcard/screen.png ./"+USER_SCREENSHOT_FOLDER+"/"+selectedDeviceEntry.getKey()+".png");
                        File file = new File("./" + MainFrame.USER_SCREENSHOT_FOLDER + "/" + selectedDeviceEntry.getKey() + ".png");
                        if (file.exists()) {
                            BufferedImage bufferedImage = null;
                            try {
                                bufferedImage = ImageIO.read(file);
                                screenshotPanel.setBufferedImage(bufferedImage);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        try {
                            Thread.sleep(10000);
                        } catch (InterruptedException interruptedException) {
//                                interruptedException.printStackTrace();
                            break;
                        }
                    }
                }
            };
            refreshThread.start();
        }
    }
    //连接设备，并开启截图进程
    private boolean connectDevice(String deviceId) {
        //1.获取分辨率，并更新至状态栏
        String getResolutionRatioCommand = "adb -s "+deviceId +" shell wm size";
        String resolutionRatio =AdbUtil.executeShellPlus(getResolutionRatioCommand);

        Pattern pattern =Pattern.compile("(\\d+x\\d+)");
        Matcher matcher=pattern.matcher(resolutionRatio);
        if(matcher.find()){
            String str = matcher.group(1);

            showResolutionRatioText.setText(str);

            String []resolutionArr = str.split("x");
            int screenWidth = Integer.parseInt(resolutionArr[0]);
            int screenHeight = Integer.parseInt(resolutionArr[1]);
            PropertiesUtil.writeValue("./"+USER_CONFIG_FOLDER+"/"+"default"+USER_CONFIG_SUFFIX,"screen.width",screenWidth+"");
            PropertiesUtil.writeValue("./"+USER_CONFIG_FOLDER+"/"+"default"+USER_CONFIG_SUFFIX,"screen.height",screenHeight+"");
            return true;
        }
        return false;
    }


    @Override
    public void actionPerformed(ActionEvent e) {
        String actionId = e.getActionCommand();
        if("connectButton".equals(actionId)){
            selectedDeviceEntry = deviceComboBox.getItemAt(0);
            if("0".equals(selectedDeviceEntry.getKey())){
                JOptionPane.showMessageDialog(null, "请选择设备！", "提示",JOptionPane.ERROR_MESSAGE);
                return;
            }
            //连接操作
            //1.分辨率
            boolean isConnected =  connectDevice(selectedDeviceEntry.getKey().toString().trim());
            if(isConnected){
                connectStatusText.setText(selectedDeviceEntry.toString()+"已连接");
                screenshotPanel.setDeviceEntry(selectedDeviceEntry);
                startScreenshotThread();
            }else{
                JOptionPane.showMessageDialog(null, "连接失败，请重试", "提示",JOptionPane.ERROR_MESSAGE);
                return;
            }

            //3.开始按钮置为可用状态
            startButton.setEnabled(true);
//            com.wjcxf.struct.Point point = new com.wjcxf.struct.Point(2,1);
//            com.wjcxf.struct.Point point2 = new com.wjcxf.struct.Point(2,1);
//            List<com.wjcxf.struct.Point> list = new ArrayList<>();
//            list.add(point);
//            list.add(point2);
//            this.screenshotPanel.getGrid().setTipsList(list,new PopStar(this.screenshotPanel.getGrid().getStarArr()));
            return;
        }
        if("refreshButton".equals(actionId)){
            deviceComboBox.removeAllItems();
            deviceMap.clear();

            //执行adb devices
            try {
                deviceMap =  (HashMap<String,String>) AdbUtil.getAllDeviceInfo();

                //遍历deviceMap
                Iterator iterator = deviceMap.entrySet().iterator();
                while (iterator.hasNext()){
                    Map.Entry entry = (Map.Entry<String,String>)iterator.next();
                    DeviceEntry<String,String> deviceEntry = new DeviceEntry<String, String>(entry.getKey().toString(),entry.getValue().toString());

                    //过滤异常设备
                    if(!"".equals(entry.getKey().toString()) && !"".equals(entry.getValue().toString())){
                        deviceComboBox.addItem(deviceEntry);
                    }
                }

                if(deviceComboBox.getItemCount() == 0){
                    deviceComboBox.addItem(new DeviceEntry<String, String>("0","请选择设备"));
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            return;
        }
        //单击事件
        if("leftLocationButton".equals(actionId)){

            if(screenshotPanel.isSelectedGrid()){
                screenshotPanel.setGridX(screenshotPanel.getGrid().getX()-1);
            }

        }else if("rightLocationButton".equals(actionId)){
            if(screenshotPanel.isSelectedGrid()){
                screenshotPanel.setGridX(screenshotPanel.getGrid().getX()+1);
            }

        }else if("upLocationButton".equals(actionId)){
            if(screenshotPanel.isSelectedGrid()){
                screenshotPanel.setGridY(screenshotPanel.getGrid().getY()-1);
            }
        }else if("downLocationButton".equals(actionId)){
            if(screenshotPanel.isSelectedGrid()){
                screenshotPanel.setGridY(screenshotPanel.getGrid().getY()+1);
            }
        }else if("leftScaleButton".equals(actionId)){
            if(screenshotPanel.isSelectedGrid()){
                screenshotPanel.setGridWidth(screenshotPanel.getGrid().getWidth()-1);
            }
        }else if("rightScaleButton".equals(actionId)){
            if(screenshotPanel.isSelectedGrid()){
                screenshotPanel.setGridWidth(screenshotPanel.getGrid().getWidth()+1);
            }
        }else if("upScaleButton".equals(actionId)){
            if(screenshotPanel.isSelectedGrid()){
                screenshotPanel.setGridHeight(screenshotPanel.getGrid().getHeight()-1);
            }
        }else if("downScaleButton".equals(actionId)){
            if(screenshotPanel.isSelectedGrid()){
                screenshotPanel.setGridHeight(screenshotPanel.getGrid().getHeight()+1);
            }

        }else if("startButton".equals(actionId)){
            startSolution();

        }else if("isMultithreading1".equals(actionId)){
            PropertiesUtil.writeValue("./"+USER_CONFIG_FOLDER+"/"+"default"+USER_CONFIG_SUFFIX,"config.multithreading","1");

        }else if("isMultithreading2".equals(actionId)){
            PropertiesUtil.writeValue("./"+USER_CONFIG_FOLDER+"/"+"default"+USER_CONFIG_SUFFIX,"config.multithreading","0");
        }else if("saveButton".equals(actionId)){
            saveUserConfig();
        }
    }
    private java.util.List<com.wjcxf.struct.Point> list = null;
    private void startSolution() {
        if(screenshotPanel.getBufferedImage() == null){
            JOptionPane.showMessageDialog(null, "未找到截图，请确保手机已经正确连接", "提示",JOptionPane.ERROR_MESSAGE);
            return;
        }
        startButton.setEnabled(false);
        String userConfigFileStr = "./"+USER_CONFIG_FOLDER+"/"+"default"+USER_CONFIG_SUFFIX;
        String multithreadingStr = PropertiesUtil.readValue(userConfigFileStr,"config.multithreading");
        String threadNumStr = PropertiesUtil.readValue(userConfigFileStr,"config.threadnum");
        String searchTimeStr = PropertiesUtil.readValue(userConfigFileStr,"config.searchtime");

        int multithreading = Integer.parseInt(multithreadingStr);

        int threadNum = Integer.parseInt(threadNumStr);
        int searchTime = Integer.parseInt(searchTimeStr);
        int [][]arr = this.screenshotPanel.getGrid().getStarArr();

        PopStar star = new PopStar(arr);
        star.show();
        PopStar maxScoreStar = new PopStar(star);

        if(multithreading == 1){
            list= PopStarSolution.MontCarloPlus2(star,threadNum,searchTime);
        }else{
            list = PopStarSolution.MontCarlo(star,searchTime);
        }
        for(int i=0;i<list.size();i++){
            maxScoreStar.click(list.get(i).getX(),list.get(i).getY());
        }
        maxScoreStar.checkGameOver();

        int isClick = JOptionPane.showConfirmDialog(null, "共检索"+PopStarSolution.solutionCount+"次，搜索分数最高为"+maxScoreStar.score+",是否执行点击脚本(放弃将重新搜索)", "提示", JOptionPane.YES_NO_CANCEL_OPTION);
        this.expectScoreLabel.setText(maxScoreStar.score+"");
        if(isClick == JOptionPane.YES_OPTION){
            for(int i=0;i<list.size();i++){
                try {
                    Thread.sleep(800);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Point mobilePosition = this.screenshotPanel.getGrid().getMobilePosition2(list.get(i).getX(),list.get(i).getY());
                String cmd = "adb -s "+selectedDeviceEntry.getKey()+" shell input tap "+mobilePosition.x+" "+mobilePosition.y;
                System.out.println(cmd);
                AdbUtil.executeShellPlus(cmd);
            }
//            this.screenshotPanel.getGrid().setTipsList(list,star);
        }
        PopStarSolution.solutionCount = 0;
        PopStarSolution.maxScorePopStar = null;
        startButton.setEnabled(true);

//        while(true){
//            if(multithreading == 1){
//                list= PopStarSolution.MontCarloPlus(star,threadNum,searchTime);
//            }else{
//                list = PopStarSolution.MontCarlo(star,searchTime);
//            }
//            PopStar tempStar = new PopStar(star);
//            for(int i=0;i<list.size();i++){
//                tempStar.click(list.get(i).getX(),list.get(i).getY());
//            }
//            if(maxScoreStar.score < tempStar.score){
//                maxScoreStar = new PopStar(tempStar);
//                expectScoreLabel.setText(""+maxScoreStar.score);
//            }
//            java.util.List<com.wjcxf.struct.Point> maxScoreClickList =  maxScoreStar.clickList;
//            java.util.List<com.wjcxf.struct.Point> currentClickList =  star.clickList;
//            if(maxScoreClickList.size() > currentClickList.size()){
//                com.wjcxf.struct.Point point = maxScoreClickList.get(currentClickList.size());
//                star.click(point.getX(),point.getY());
//                Point mobilePosition = this.screenshotPanel.getGrid().getMobilePosition(point.getX(),point.getY());
//                String cmd = "adb -s "+selectedDeviceEntry.getKey()+" shell input tap "+mobilePosition.x+" "+mobilePosition.y;
//                AdbUtil.executeShellPlus(cmd);
//            }
//
//            if(star.checkGameOver()){
//                break;
//            }
//        }





    }

    @Override
    public void itemStateChanged(ItemEvent e) {
        if(e.getSource() == deviceComboBox){
            if (e.getStateChange() == ItemEvent.SELECTED) {
                DeviceEntry<String,String> deviceEntry = (DeviceEntry<String, String>) e.getItem();

                if("".equals(deviceEntry.getValue().toString().trim()) || "".equals(deviceEntry.getKey().toString().trim())){
                    JOptionPane.showMessageDialog(null, "无效的设备id！", "提示",JOptionPane.ERROR_MESSAGE);
                    return ;
                }

            }
            return;
        }
    }
    private boolean pressALT = false;
    private boolean pressK = false;
    @Override
    public void keyTyped(KeyEvent e) {

    }

    @Override
    public void keyPressed(KeyEvent e) {
        switch (e.getKeyCode()) {
            case KeyEvent.VK_ALT:
                pressALT = true;
                break;
            case KeyEvent.VK_K:
                pressK = true;
                break;
            default:
                break;
        }
        if (pressALT && pressK) {
            System.out.println("ALT + K");
            //强制退出
            System.exit(0);
        }
        System.out.println();
        int code = e.getKeyCode();
        if(KeyEvent.VK_A == code){
            System.out.println("a");
            if(screenshotPanel.isSelectedGrid()){
                screenshotPanel.setGridX(screenshotPanel.getGrid().getX()-1);
            }
        }
        if(KeyEvent.VK_W == code){
            System.out.println("w");
            if(screenshotPanel.isSelectedGrid()){
                screenshotPanel.setGridY(screenshotPanel.getGrid().getY()-1);
            }
        }
        if(KeyEvent.VK_S == code){
            System.out.println("s");
            if(screenshotPanel.isSelectedGrid()){
                screenshotPanel.setGridY(screenshotPanel.getGrid().getY()+1);
            }
        }
        if(KeyEvent.VK_D == code){
            System.out.println("d");
            if(screenshotPanel.isSelectedGrid()){
                screenshotPanel.setGridX(screenshotPanel.getGrid().getX()+1);
            }
        }

        if(KeyEvent.VK_J == code){
            System.out.println("j");
            if(screenshotPanel.isSelectedGrid()){
                screenshotPanel.setGridWidth(screenshotPanel.getGrid().getWidth()-1);
            }
        }
        if(KeyEvent.VK_I == code){
            System.out.println("i");
            if(screenshotPanel.isSelectedGrid()){
                screenshotPanel.setGridHeight(screenshotPanel.getGrid().getHeight()-1);
            }
        }
        if(KeyEvent.VK_K == code){
            System.out.println("k");
            if(screenshotPanel.isSelectedGrid()){
                screenshotPanel.setGridHeight(screenshotPanel.getGrid().getHeight()+1);
            }
        }
        if(KeyEvent.VK_L == code){
            System.out.println("l");
            if(screenshotPanel.isSelectedGrid()){
                screenshotPanel.setGridWidth(screenshotPanel.getGrid().getWidth()+1);
            }
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {
        switch (e.getKeyCode()) {
            case KeyEvent.VK_ALT:
                pressALT = false;
                break;
            case KeyEvent.VK_K:
                pressK = false;
                break;
            default:
                break;
        }
    }
    public class InputCharFilter extends PlainDocument {

        @Override
        public void insertString(int offs, String str, AttributeSet a)
                throws BadLocationException {

            Pattern pattern =Pattern.compile("^[0-9]*[1-9][0-9]*$");
            Matcher matcher=pattern.matcher(str);
            if(!matcher.find()){
                return;
            }

            super.insertString(offs, str, a);
        }

    }

}
